package freespiritsocial.io.user.viewmodel

import com.facebook.AccessToken
import com.facebook.GraphRequest
import com.facebook.GraphResponse
import freespiritsocial.io.user.data.model.bean.DiscoverFriendPojo
import freespiritsocial.io.user.network.apiService
import freespiritsocial.io.user.viewmodel.delegates.IPeopleApi
import freespiritsocial.io.user.viewmodel.delegates.PeopleDelegate
import kotlinx.coroutines.suspendCancellableCoroutine
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import org.json.JSONArray
import kotlin.coroutines.resume

class DiscoverFriendViewModel: BaseViewModel(),IPeopleApi by PeopleDelegate() {

    fun facebookFriend(token: AccessToken,callback: (List<String>) -> Unit) {
        requestNoCheck({
            findFacebook(token)
        },{
            callback.invoke(it)
        })
    }

    fun findFriends(ids: List<String>,callback: (List<DiscoverFriendPojo>) -> Unit) {
        if (ids.isEmpty()) return
        request({
            apiService.findFriend(ids)
        },{
            callback(it)
        })
    }

    private suspend fun findFacebook(token: AccessToken) = suspendCancellableCoroutine<List<String>> {
        GraphRequest.newMyFriendsRequest(token) { jsonArray: JSONArray,graphResponse: GraphResponse ->
            val list = arrayListOf<String>()
            if (jsonArray.length() == 0) it.resume(list)
            for (i in 0 until jsonArray.length()) {
                list.add(jsonArray.getJSONObject(i).getString("id"))
            }
            it.resume(list)
        }.executeAsync()
    }
}